package com.xiaoye.qbproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoye.qbproject.domain.QbSubject;
import com.xiaoye.qbproject.domain.QbSubjectSubscription;
import com.xiaoye.qbproject.mapper.QbSubjectMapper;
import com.xiaoye.qbproject.mapper.QbSubjectSubscriptionMapper;
import com.xiaoye.qbproject.service.QbSubjectService;
import com.xiaoye.qbproject.service.QbSubjectSubscriptionService;
import com.xiaoye.qbproject.service.web.TokenService;
import com.xiaoye.qbproject.util.StringUtils;
import com.xiaoye.qbproject.vo.SubjectSubscriptionVo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【QB_SUBJECT(情报专题)】的数据库操作Service实现
 * @createDate 2025-01-14 19:28:41
 */
@Service
public class QbSubjectServiceImpl extends ServiceImpl<QbSubjectMapper, QbSubject>
        implements QbSubjectService {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private QbSubjectSubscriptionMapper qbSubjectSubscriptionMapper;
    @Autowired
    private QbSubjectSubscriptionService qbSubjectSubscriptionService;

    /**
     * @param qbSubject
     * @param request
     * @description: 情报专题列表 包含是否订阅
     * @author: ChenYao
     * @return: java.util.List<com.xiaoye.qbproject.domain.QbSubject>
     * @ceateDate: 2025/1/14 下午10:58
     */
    @Override
    public List<QbSubject> getSubjectListAndSub(QbSubject qbSubject, HttpServletRequest request) {


        LambdaQueryWrapper<QbSubject> queryWrapper = Wrappers.<QbSubject>lambdaQuery();
        String name = qbSubject.getName();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(QbSubject::getName, name);
        }
        List<QbSubject> qbSubjects = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(qbSubjects)) {
            return Collections.emptyList();
        }
        // 如果 用户id 不为空, 则查询是否订阅
        String userId = tokenService.getUserId(request);
        if (!CollectionUtils.isEmpty(qbSubjects) || StringUtils.isNotBlank(userId)) {
            List<QbSubjectSubscription> qbSubjectSubscriptions = qbSubjectSubscriptionMapper.selectList(Wrappers
                    .<QbSubjectSubscription>lambdaQuery()
                    .eq(QbSubjectSubscription::getUserId, userId)
                    .in(QbSubjectSubscription::getSubjectId, qbSubjects.stream().map(QbSubject::getId).collect(Collectors.toList()))
            );
            // 更新订阅时间
            qbSubjects.forEach(qbSubjectSubscription -> qbSubjectSubscription.setLastUpdatedTime(new Date()));

            if (CollectionUtils.isNotEmpty(qbSubjectSubscriptions)) {
                qbSubjectSubscriptions.forEach(qbSubjectSubscription -> {
                    for (QbSubject qbSubject1 : qbSubjects) {
                        if (qbSubject1.getId().equals(qbSubjectSubscription.getSubjectId())) {
                            qbSubject1.setIsSubscribed(true);

                        }
                    }
                });
            }
        }
        return qbSubjects;
    }

    /**
     * @param list
     * @description: 情报专题删除
     * @author: ChenYao
     * @return: void
     * @ceateDate: 2025/1/15 下午5:02
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delSubject(List<String> list) {
        for (String id : list) {
            // 删除情报专题
            baseMapper.deleteById(id);
            // 删除情报专题订阅
            qbSubjectSubscriptionMapper.delete(Wrappers.<QbSubjectSubscription>lambdaQuery().eq(QbSubjectSubscription::getSubjectId, id));
        }
    }

    /**
     * @param qbSubject
     * @param request
     * @description: 获取我的订阅专题列表
     * @author: ChenYao
     * @return: java.util.List<com.xiaoye.qbproject.domain.QbSubject>
     * @ceateDate: 2025/1/15 下午5:07
     */
    @Override
    public List<QbSubject> getMySubscriptionSubjectList(QbSubject qbSubject, HttpServletRequest request) {
        String userId = tokenService.getUserIdIsNullThrowException(request);
        List<QbSubject> qbSubjects = baseMapper.selectMySubscriptionSubjectList(qbSubject, userId);
        if (CollectionUtils.isNotEmpty(qbSubjects)) {
            // 查询专题最近更新时间
            for (QbSubject qbSubject1 : qbSubjects) {
                qbSubject1.setIsSubscribed(true);
                qbSubject1.setLastUpdatedTime(new Date());
            }
        }
        return qbSubjects;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editSubject(QbSubject qbSubject) {
        Boolean isSubscribed = qbSubject.getIsSubscribed();
        if (isSubscribed != null) {
            SubjectSubscriptionVo subjectSubscriptionVo = new SubjectSubscriptionVo();
            subjectSubscriptionVo.setSubjectIds(Collections.singletonList(qbSubject.getId()));
            subjectSubscriptionVo.setIsSubscribe(isSubscribed);
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
            qbSubjectSubscriptionService.setSubjectSubscription(subjectSubscriptionVo, request);
        }
        return baseMapper.updateById(qbSubject);
    }
}




